import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:rainflutter/Tools/http_dio.dart';

class AsyncAwait extends StatefulWidget {
  @override
  _AsyncAwaitState createState() => _AsyncAwaitState();
}

class _AsyncAwaitState extends State<AsyncAwait>
    with SingleTickerProviderStateMixin {
  AnimationController _controller;
  String url =
      'https://wap.baidu.com';
  HttpUtil http = HttpUtil();
  String text = '测试';
  String html = '';

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(vsync: this);
    getData().then((value) {
      print('我getData运行完了');
      text = '执行完毕';
      html = value;
      setState(() {});
    });

    print('开始执行');
    for (var i = 0; i < 10000; i++) {
      if (i / 1 == 0) {
        print(1);
      }
    }
    getData().then((value) => print('我getData运行完了'));

    getData2().then((value) => print('我getData2也运行完了'));
    print('我不管你哦');

    Future.delayed(Duration(seconds: 1), () {
      int age = 18;
      return age;
    }).then((onValue) {
      onValue++;
      print('age $onValue');
    });
  }

  @override
  void dispose() {
    super.dispose();
    _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('async')),
      body: ListView(
        children: [
          Text(text),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Html(shrinkWrap: true, data: html),
          )
        ],
      ),
    );
  }

  //代码清单 1-1
  //HTTP的get请求返回值为Future<String>类型，即其返回值未来是一个String类型的值
  //async关键字声明该函数内部有代码需要延迟执行
  Future<String> getData() async {
    //await关键字声明运算为延迟执行，然后return运算结果
    print('开始执行运行getData');
    print('result1');
    String result1 = await http.get(url);
    for (var i = 0; i < 1000; i++) {
      print(1);
    }

    return result1;
  }

  Future<String> getData2() async {
    //await关键字声明运算为延迟执行，然后return运算结果
    print('开始执行运行getData2');
    String result2 = await http.get(url);
    print('result2');

    return result2;
  }
}
